package com.zzl.study.demo.config;

import com.alibaba.cloud.ai.memory.redis.RedissonRedisChatMemoryRepository;
import com.zzl.study.demo.properties.RedisMemoryProperties;
import org.redisson.config.Config;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 对话记忆配置类
 *
 * @author: zhangzl
 * @date: 2025/10/14 9:56
 * @version: 1.0
 */
@Configuration
@EnableConfigurationProperties(RedisMemoryProperties.class)
public class RedisMemoryAutoConfiguration {

    /**
     * 向Spring容器中注入一个基于Redis的Redisson框架对话记忆存储仓库
     *
     * @param redisMemoryProperties Redis属性配置
     * @return 基于Redis的Redisson框架对话记忆存储仓库
     */
    @Bean
    public RedissonRedisChatMemoryRepository redissonRedisChatMemoryRepository(RedisMemoryProperties redisMemoryProperties) {
        return RedissonRedisChatMemoryRepository.builder()
                .redissonConfig(buildRedissonConfig(redisMemoryProperties))
                .build();
    }

    /**
     * 构建Redisson框架的配置信息
     *
     * @return Redisson框架的配置信息
     */
    private Config buildRedissonConfig(RedisMemoryProperties redisMemoryProperties) {
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://" + redisMemoryProperties.getHost() + ":" + redisMemoryProperties.getPort())
                .setTimeout(redisMemoryProperties.getTimeout())
                .setConnectionPoolSize(redisMemoryProperties.getMaxPoolSize())
                .setDatabase(redisMemoryProperties.getDatabase())
                .setPassword(redisMemoryProperties.getPassword());
        return config;
    }

}
